import React from 'react';
import { createForm } from 'rc-form';
import { connect } from 'react-redux';
import { Card, List, InputItem, Picker, TextareaItem, WhiteSpace, Toast, Modal, WingBlank } from 'antd-mobile';

import { district, provinceLite } from 'antd-mobile-demo-data';

import {withClient} from '../../hoc';

import {getPickerData, getLabelValueData, getNotEmptyObj} from '../../utils/crmUtils';

import NavBar from '../../components/common/NavBar';
import Title from '../../components/common/Title';
import Pick from '../../components/common/Picker';
import SearchModal from '../../components/common/Modal';

import cities from '../../utils/cityData';

import './index.sass';

@withClient
@createForm()
@connect((state) => ({access_token: state.token.access_token}))
export default class AddCustomer extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            customerInsuredNumberDatas: [],
            customerLevelDatas: [],
            customerStaffSizeDatas: [],
            allProduct: [],
            customerParameterSet: [],
            customerDemand: [],
            source: [],
            companyNum: [],
            businessTypes: [],
            isQxb: false,
            qxbVisible: false,
        }
    }

    checkName = async() => {
        const cName = this.props.form.getFieldValue('cName');
        const res = await this.props.client.post('/crm/api/mobile/customer/checkCName',{cName, customerType: 3, access_token: this.props.access_token});
        if(Number(res.status) !== 0){
            Toast.fail(res.msg, 1);
        }else{
            if(res.data){
                Toast.fail(res.data.msg, 1);
            }
        }
    }

    openGong = () => {
        console.log('gong')
        const cName = this.props.form.getFieldValue('cName');
        if(cName && cName.length > 1){
            console.log('gong-in')
            Toast.success(cName);
            this.setState({qxbVisible: true})
        }else{
            Toast.fail('请至少2个字进行搜索', 1);
        }
    }

    searchQxb = (value) => {

    }

    save = () => {
        this.props.form.validateFields(async(err, values) => {
            if(!err){
                console.log(values);
                const p = cities.filter(item => Number(item.value) === Number(values.city[0]))[0];
                const c = p.children.filter(item => Number(item.value) === Number(values.city[1]))[0];
                values.province = values.city[0];
                values.provinceName = p.label;
                values.city = values.city[1];
                values.cityName = c.label;
                values.customerSource = values.customerSource[1];
                values.businessType = values.businessType[1];
                const res = await this.props.client.post('/crm/api/mobile/customer/addCustomerAndContact',
                {
                    ...getNotEmptyObj(values), 
                    customerType: 3,
                    access_token: this.props.access_token,
                }
                );
                if(Number(res.status) === 0){
                    this.props.history.push('/customer');
                }
            }else{
                const msg = Object.values(err)[0].errors[0].message;
                Toast.fail(msg, 1);
            }
        })
    }

    getOptions = async () => {
        const [
            customerParameterSet,
            allProduct,
            customerDemand,
            source,
        ] = await Promise.all([
            this.props.client.post('/crm/api/mobile/customerParameterSet/getSet', { access_token: this.props.access_token }),
            this.props.client.post('/crm/api/mobile/product/getAllEnableProduct', { access_token: this.props.access_token }),
            this.props.client.post('/crm/api/mobile/customerDemand/getCustomerDemand', {access_token: this.props.access_token}),
            this.props.client.post('/crm/api/mobile/dictionary/getDataList', { access_token: this.props.access_token }),
        ]);
        let {customerInsuredNumberDatas, customerLevelDatas, customerStaffSizeDatas} = customerParameterSet.data;
        this.setState({
            customerInsuredNumberDatas: getLabelValueData(customerInsuredNumberDatas),
            customerLevelDatas: getLabelValueData(customerLevelDatas),
            customerStaffSizeDatas: getLabelValueData(customerStaffSizeDatas),
            allProduct: getLabelValueData(allProduct.data, 'name', 'id'),
            // customerParameterSet: getLabelValueData(customerParameterSet.data),
            customerDemand: getLabelValueData(customerDemand.data, 'demand', 'id'),
            source: getPickerData(source.data.souces, 'dictName', 'id', 'sons'),
            companyNum: getPickerData(source.data.companyNums, 'dictName', 'id', 'sons'),
            businessTypes: getPickerData(source.data.businessTypes, 'typeName', 'id', 'sons'),
        });
    }

    componentDidMount() {
        if (__CLIENT__) {
            setTimeout(async () => {
                await this.getOptions();
            }, 0);
        }
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;

        const {
            customerInsuredNumberDatas,
            customerLevelDatas,
            customerStaffSizeDatas,
            allProduct,
            // customerParameterSet,
            customerDemand,
            source,
            companyNum,
            businessTypes,
            isQxb,

            qxbVisible,
        } =this.state;
        return (
            <div className='page-add-customer-container'>

                <SearchModal
                    search
                    autoFocus
                    visible={this.state.qxbVisible}
                    onCancel={() => this.setState({qxbVisible: false})}
                    placeholder={'请至少输入4个字搜索'}
                    defaultValue={getFieldValue('cName')}
                    onSubmit={this.searchQxb}
                >
                
                </SearchModal>

                <NavBar
                    title={'新增客户'}
                    cancelText='关闭'
                    leftClick={() => { 
                        const alertInstance = Modal.alert('退出','当前页面还没有保存，是否确定关闭？', [
                            { text: '取消', onPress: () => alertInstance.close(), style: 'default' },
                            { text: '确定', onPress: () => this.props.history.goBack() },
                        ]);
                    }}
                    rightButton={[<span key={'save'} onClick={this.save}>保存</span>]}
                />
                <div className='page-add-customer-content'>
                    <WingBlank size='md'><Card>
                        <Card.Header title={<Title title='客户基本信息' />} />
                        <Card.Body>
                            <List className='global-list'>

                                {getFieldDecorator('type', {
                                    validateFirst: true,
                                    initialValue: [0],
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写客户类型');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="客户类型"
                                    extra="必填"
                                    cols={1}
                                    data={[{ label: '企业', value: 0 }, { label: '社会组织', value: 1 }, { label: '境外客户', value: 2 }]}
                                    title="客户类型"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                    disabled={isQxb}
                                >
                                    <List.Item arrow="down">客户类型</List.Item>
                                </Picker>)}

                                {getFieldDecorator('cName', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写客户名称')
                                            }else if(value < 2){
                                                callback('客户名称不可少于2个字')
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<InputItem 
                                    clear 
                                    placeholder="必填" 
                                    onBlur={this.checkName}
                                    extra={isQxb ? '' : <i className='crmiconfont crmicon-qiyegongshangxinxi'/>}
                                    onExtraClick={this.openGong}
                                    disabled={isQxb}
                                    >
                                    客户名称
                                </InputItem>)}

                                {getFieldDecorator('city', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                              console.log(value);
                                            if(!value){
                                                callback('请填写客户所在地');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="客户所在地"
                                    extra="必填"
                                    cols={2}
                                    data={cities}
                                    title="客户所在地"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                    disabled={isQxb}
                                >
                                    <List.Item arrow="down">客户所在地</List.Item>
                                </Picker>)}

                                {getFieldDecorator('address', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem 
                                    clear 
                                    placeholder="请填写详细地址" 
                                    disabled={isQxb}
                                    >
                                    {' '}
                                </InputItem>)}

                                {getFieldDecorator('customerSource', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写客户来源');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="客户来源"
                                    extra="必填"
                                    cols={2}
                                    data={source}
                                    title="客户来源"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">客户来源</List.Item>
                                </Picker>)}

                                {getFieldDecorator('customerParamLevel', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写客户等级');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="客户等级"
                                    extra="必填"
                                    cols={1}
                                    data={customerLevelDatas}
                                    title="客户等级"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">客户等级</List.Item>
                                </Picker>)}

                                {getFieldDecorator('customerStaffSize', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写公司规模');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="公司规模"
                                    extra="必填"
                                    cols={1}
                                    data={customerStaffSizeDatas}
                                    title="公司规模"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">公司规模</List.Item>
                                </Picker>)}

                                {getFieldDecorator('customerInsuredNumber', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写预计参保人数');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="预计参保人数"
                                    extra="必填"
                                    cols={1}
                                    data={customerInsuredNumberDatas}
                                    title="预计参保人数"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">预计参保人数</List.Item>
                                </Picker>)}

                                {getFieldDecorator('insureStatus', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<Pick
                                    key="员工参保情况"
                                    data={[{ label: '自缴', value: 1 }, { label: '代缴', value: 2 }, { label: '未缴', value: 3 }, { label: '其他', value: 4}]}
                                    title="员工参保情况"
                                >
                                    员工参保情况
                                </Pick>)}

                                {getFieldDecorator('cooperationIntention', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value || value[0] === undefined){
                                                callback('请填写合作意向');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Pick
                                    key="合作意向"
                                    placeholder='必填'
                                    data={allProduct}
                                    title="合作意向"
                                >
                                    合作意向
                                </Pick>)}

                                {getFieldDecorator('customerDemand', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<Pick
                                    key="客户需求"
                                    data={customerDemand}
                                    title="客户需求"
                                >
                                    客户需求
                                </Pick>)}

                                {getFieldDecorator('remark', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<TextareaItem rows={5} count={100} placeholder="点击填写" title="备注" />)}

                            </List>
                        </Card.Body>
                    </Card></WingBlank> 

                    <WhiteSpace />

                    <WingBlank size='md'><Card>
                        <Card.Header title={<Title title='企业基本信息' />} />
                        <Card.Body>
                            <List className='global-list'>

                                {getFieldDecorator('businessType', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写行业类型');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="行业类型"
                                    extra="必填"
                                    cols={2}
                                    data={businessTypes}
                                    title="行业类型"
                                    onOk={e => console.log('ok', e)}
                                    disabled={isQxb}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">行业类型</List.Item>
                                </Picker>)}

                                {getFieldDecorator('customerMail', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem disabled={isQxb} clear placeholder="请填写">
                                    邮件
                                </InputItem>)}

                                {getFieldDecorator('customerPhone', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem disabled={isQxb} clear placeholder="请填写">
                                    电话
                                </InputItem>)}

                                {getFieldDecorator('customerAddress', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem disabled={isQxb} clear placeholder="请填写">
                                    办公地址
                                </InputItem>)}

                                {getFieldDecorator('currentCustomerMail', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="请填写">
                                    邮件(现)
                                </InputItem>)}

                                {getFieldDecorator('currentCustomerPhone', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="请填写">
                                    电话(现)
                                </InputItem>)}

                                {getFieldDecorator('currentCustomerAddress', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="请填写">
                                    办公地址(现)
                                </InputItem>)}

                            </List>
                        </Card.Body>
                    </Card></WingBlank>

                    <WhiteSpace />

                    <WingBlank size='md'><Card>
                        <Card.Header title={<Title title='联系人信息' />} />
                        <Card.Body>
                            <List className='global-list'>

                                {getFieldDecorator('name', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写联系人姓名');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="必填">
                                    姓名
                                </InputItem>)}

                                {getFieldDecorator('gender', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写联系人性别');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="gender"
                                    extra="必填"
                                    cols={1}
                                    data={[{ label: '男', value: 1 }, { label: '女', value: 2 }, { label: '保密', value: 0 }]}
                                    title="性别"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">性别</List.Item>
                                </Picker>)}

                                {getFieldDecorator('position', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写联系人职位');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="必填">
                                    联系人职位
                                </InputItem>)}

                                {getFieldDecorator('contactRole', {
                                    validateFirst: true,
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            if(!value){
                                                callback('请填写联系人角色');
                                            }else{
                                                callback();
                                            }
                                          }
                                        }
                                    ]
                                })(<Picker
                                    key="联系人角色"
                                    extra="必填"
                                    cols={1}
                                    data={[{ label: '社保联系人', value: 1 }, { label: '授权管理员', value: 2 }, { label: '跟进联系人', value: 3 }, { label: '合同授权人', value: 4 }]}
                                    title="联系人角色"
                                    onOk={e => console.log('ok', e)}
                                    onDismiss={e => console.log('dismiss', e)}
                                >
                                    <List.Item arrow="down">联系人角色</List.Item>
                                </Picker>)}

                                {getFieldDecorator('mobile', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="请填写">
                                    手机号码
                                </InputItem>)}

                                {getFieldDecorator('fixedTelephone', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<InputItem clear placeholder="请填写">
                                    固定电话
                                </InputItem>)}

                                {getFieldDecorator('contactRemark', {
                                    rules: [
                                        {
                                          validator: (rules, value, callback) => {
                                            callback();
                                          }
                                        }
                                    ]
                                })(<TextareaItem rows={5} count={100} placeholder="点击填写" title="备注" />)}

                            </List>
                        </Card.Body>
                    </Card></WingBlank>
                </div>
            </div>
        );
    }
}